import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import Evaluation from '../views/Evaluation.vue'
import HazardManagement from '../views/HazardManagement.vue'
import ReportManagement from '../views/ReportManagement.vue'
import KnowledgeBase from '../views/KnowledgeBase.vue'
import UserManagement from '../views/UserManagement.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '系统登录', requiresAuth: false }
  },
  {
    path: '/evaluation',
    name: 'Evaluation',
    component: Evaluation,
    meta: { title: '安全评价', requiresAuth: true }
  },
  {
    path: '/hazard',
    name: 'HazardManagement',
    component: HazardManagement,
    meta: { title: '隐患跟踪', requiresAuth: true }
  },
  {
    path: '/reports',
    name: 'ReportManagement',
    component: ReportManagement,
    meta: { title: '报告管理', requiresAuth: true }
  },
  {
    path: '/knowledge',
    name: 'KnowledgeBase',
    component: KnowledgeBase,
    meta: { title: '知识库', requiresAuth: true }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: { title: '人员管理', requiresAuth: true, requiresAdmin: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  const isAuthenticated = !!userStore.userInfo.id
  const userRole = userStore.userInfo.role
  
  // 如果要访问登录页面且已经登录，直接跳转到首页
  if (to.path === '/login' && isAuthenticated) {
    next('/users')
    return
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
    return
  }
  
  // 检查管理员权限
  if (to.meta.requiresAdmin && userRole !== 'admin') {
    next('/evaluation')
    return
  }
  
  next()
})

export default router
